using System;
using System.ComponentModel;
using System.Reflection;

namespace MovieDB.Common
{
    public static class EnumConversions
    {
        public static string GetEnumDescription(this Enum enumValue)
        {
            //get the enumerator type
            Type type = enumValue.GetType();

            //get the member info
            MemberInfo[] memberInfo = type.GetMember(enumValue.ToString());

            //if there is member information
            if (memberInfo.Length > 0)
            {
                //we default to the first member info, as it's for the specific enum value
                object[] attributes = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);

                //return the description if it's found
                if (attributes != null && attributes.Length > 0)
                {
                    return ((DescriptionAttribute) attributes[0]).Description;
                }
            }

            //if there's no description, return the string value of the enum
            return enumValue.ToString();
        }

        public static T ParseAsEnum<T>(this string value)
        {
            return (T) Enum.Parse(typeof (T), value);
        }

        public static T ParseEnumSafe<T>(this string value, T defaultValue)
        {
            T result = defaultValue;
            try
            {
                result = (T) Enum.Parse(typeof (T), value);
            }
            catch {}

            return result;
        }
    }
}